package org.example.globalHandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 想用在开启
 */
//@ControllerAdvice(basePackages = "org.example.controller")
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @ExceptionHandler(Exception.class)
    public void handler(Exception e, HttpServletRequest request, HttpServletResponse response){
        String remoteAddr = request.getRemoteAddr();
        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();
        StringBuilder message = new StringBuilder();
        message.append("用户");
        message.append(remoteAddr);
        message.append("在请求当前资源:");
        message.append(requestURI);
        message.append(";发生问题;");
        message.append("原因如下：");
        message.append(e.getMessage());
        logger.info(message.toString());
        try {
            response.sendRedirect(contextPath+"/error.html");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
